package keyfun.filesystem
{
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	import flash.filesystem.File;
	import flash.errors.IOError;
	import flash.events.Event;
	/**
	 * ...
	 * @author Key Hui
	 */
	public class FileManager 
	{
		
		public static function getJsonDataFromDocumentFolder(filePath:String):Object
		{
			var file:File = File.documentsDirectory.resolvePath(filePath);
			return getJsonData(file);
		}
		
		public static function getJsonDataFromApplicationFolder(filePath:String):Object
		{
			var file:File = File.applicationDirectory.resolvePath(filePath);
			return getJsonData(file);
		}
		
		public static function getJsonData(file:File):Object
		{			
			var result:String = "";
			
			trace("getJsonData:" + file.nativePath);
			
			try 
			{
				var fileStream:FileStream = new FileStream();
				fileStream.open(file, FileMode.READ);
				result = fileStream.readUTFBytes(fileStream.bytesAvailable);
				fileStream.close();
			}
			catch(e:IOError)
			{
				trace("getJsonData:IOError:" + file.nativePath);
			}

			if (result.length > 0)
			{
				//trace("result:" + result);
				try
				{
					var jsonObj:Object = JSON.parse(result);
					return jsonObj;
				}
				catch (e:Error)
				{
					trace("JSON Error:Data");
					trace("result:" + result);
				}
			}
			return null;
		}
		
		public static function exportJSON(dataStr:String, file:File):void
		{
			try
			{
				var fileStream:FileStream = new FileStream();
				fileStream.openAsync(file, FileMode.WRITE);
				fileStream.writeUTFBytes(dataStr);
				fileStream.addEventListener(Event.CLOSE, fileClosed);
				fileStream.close();
				
				trace("exportJSON:Save to:" + file.nativePath);
			}
			catch (e:Error)
			{
				trace("exportJSON:Error");
			}
		}
		
		public static function appendData(dataStr:String, file:File):void
		{
			try
			{
				if (file.exists)
				{
					var fileStream:FileStream = new FileStream();
					fileStream.open(file, FileMode.APPEND);
					fileStream.writeUTFBytes(dataStr + "\r\n");
					fileStream.addEventListener(Event.CLOSE, fileClosed);
					fileStream.close();
					
					trace("appendData:Save to:" + file.nativePath);
				}
				else
				{
					trace("appendData:No FilePath");
				}
			}
			catch (e:Error)
			{
				trace("appendData:Error");
			}
		}
		
		private static function fileClosed(e:Event):void
		{
			trace("The file saved.");
		}
	
	}

}